package com.ruibang.glass.material.service;

import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class SerialINNumberGenerator {
    private static final String PREFIX = "IN";
    private static final int MAX_SEQUENCE = 999;
    private static final int SEQUENCE_LENGTH = 3; // 因为序列号是000到999，所以长度为3
    private static final String DATE_FORMAT = "yyyyMMdd";

    public static String generateNextSerialNumber(String originalSerialNumber) {
        // 获取当前日期并格式化为yyyyMMdd
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        String currentDate = sdf.format(new Date());

        // 如果没有传入原始编号或原始编号格式不正确，则使用当前日期和001作为序列号
        if (originalSerialNumber == null || !originalSerialNumber.startsWith(PREFIX) || originalSerialNumber.length() != 13) {
            return PREFIX + currentDate + String.format("%0" + SEQUENCE_LENGTH + "d", 1);
        }

        // 移除前缀
        // 提取时间部分和序列号部分
        String oldDatePart = originalSerialNumber.substring(2, 10);
        String sequencePart = originalSerialNumber.substring(10);

        // 将序列号转换为整数并加1
        int seqInt = Integer.parseInt(sequencePart);
        int newSeqInt = (seqInt + 1) % (MAX_SEQUENCE + 1); // 使用(MAX_SEQUENCE + 1)确保取模后得到0-999的范围

        // 格式化新的序列号
        String newSequencePart = String.format("%0" + SEQUENCE_LENGTH + "d", newSeqInt);

        // 构建新的编号
        String newSerialNumber = PREFIX + currentDate + newSequencePart;
        return newSerialNumber;
    }

    public static void main(String[] args) {
        // 假设上次的编号是 IN20240201999
        String lastSerialNumber = "IN20240201001";
        String nextSerialNumber = generateNextSerialNumber(lastSerialNumber);
        System.out.println(nextSerialNumber); // 输出应该是 IN当前日期000 或类似（取决于当前日期）
    }
}

